package com.example.pc.system_broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.pc.system_broadcastreceiver.receiver.NetWorkBroadcastReceiver;
import com.example.pc.system_broadcastreceiver.receiver.ScreenActionBroadcastReceiver;
import com.example.pc.system_broadcastreceiver.utils.NetworkUtils;

public class MainActivity extends AppCompatActivity {

    private MsgBroadcastReceiver msgReceiver;

    class BatteryBroadcastReceiverVip extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_BATTERY_OKAY.equals(intent.getAction())) {
                tv_show.setText("电量已恢复，可以使用!");
            } else if (Intent.ACTION_BATTERY_LOW.equals(intent.getAction())) {
                tv_show.setText("电量过低，请尽快充电！");
            } else if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                Bundle bundle = intent.getExtras();
// 获取当前电量
                int current = bundle.getInt(BatteryManager.EXTRA_LEVEL);
// 获取总电量
                int total = bundle.getInt(BatteryManager.EXTRA_SCALE);
                StringBuffer sb = new StringBuffer();
                sb.append("当前电量为：" + (int) (current * 100.0 / total) + "%");
// 如果当前电量小于总电量的20%
                if (current * 1.0 / total < 0.2) {
                    sb.append("--电量过低，请尽快充电！");
                } else {
                    sb.append("--电量足够，请放心使用！");
                }
                tv_show.setText(sb.toString());
            }
        }
    }

    private NetWorkBroadcastReceiver netWorkBroadcastReceiver;
    private TextView tv_show;
    private EditText et_code;
    private ScreenActionBroadcastReceiver screenActionBroadcastReceiver;


    private BatteryBroadcastReceiverVip batteryReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_show = findViewById(R.id.tv_show);
        et_code = findViewById(R.id.et_code);

        netWorkBroadcastReceiver = new NetWorkBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(netWorkBroadcastReceiver, intentFilter);


        screenActionBroadcastReceiver = new ScreenActionBroadcastReceiver();
        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter1.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(screenActionBroadcastReceiver, intentFilter1);


        batteryReceiver = new BatteryBroadcastReceiverVip();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        filter.addAction(Intent.ACTION_BATTERY_LOW);
        filter.addAction(Intent.ACTION_BATTERY_OKAY);
        registerReceiver(batteryReceiver, filter);


        IntentFilter filterMsg = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        filterMsg.setPriority(Integer.MAX_VALUE);
        msgReceiver = new MsgBroadcastReceiver();
        registerReceiver(msgReceiver, filterMsg);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (netWorkBroadcastReceiver != null)
            unregisterReceiver(netWorkBroadcastReceiver);

        if (screenActionBroadcastReceiver != null)
            unregisterReceiver(screenActionBroadcastReceiver);

        if (batteryReceiver != null)
            unregisterReceiver(batteryReceiver);

        if (msgReceiver != null)
            unregisterReceiver(msgReceiver);
    }

    public void getNetworkState(View view) {

        int apnType = NetworkUtils.getAPNType(this);

//        tv_show.setText(apnType == 0 ? "无网络" : (apnType == 1 ? "Wifi" : (apnType == 2 ? "2G" : (apnType == 3 ? "3G" : (apnType == 4 ? "4G" : "未知状态")))));

        switch (apnType) {
            case 1:
                tv_show.setText("wifi");
                break;
            case 2:
            case 3:
            case 4:
                tv_show.setText("移动网络");
                break;
            default:
                tv_show.setText("无网络");
                break;
        }


    }


    public class MsgBroadcastReceiver extends BroadcastReceiver {

        String TAG = MsgBroadcastReceiver.class.getSimpleName();
        // 短信广播的动作
        public static final String MSG_RECEIVER_ACTION = "android.provider.Telephony.SMS_RECEIVED";

        @Override
        public void onReceive(Context context, Intent intent) {
// 获取短信广播携带的数据包Bundle
            Bundle bundle = intent.getExtras();
// 通过查看源码可知，短信的发送意图为pdus。取pdus内容,转换为Object[]
            Object[] pdus = (Object[]) bundle.get("pdus");
// 解析短信
            SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < messages.length; i++) {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            }
// 获取短信的联系人号码
            String send = messages[0].getDisplayOriginatingAddress();
// 发送时间
            long timestampMillis = messages[0].getTimestampMillis();
//短信内容
            StringBuffer sb = new StringBuffer();
            for (SmsMessage smsMessage : messages) {
                String body = smsMessage.getDisplayMessageBody();
                sb.append(body);
            }
// 短信发送的广播是系统的有序广播，有序广播可以通过abortBroadcast()的方法来结束广播
            Log.d(TAG, "onReceive: ---send--" + send);
            Log.d(TAG, "onReceive:---body--" + sb.toString());
            Log.d(TAG, "onReceive:---timestampMillis--" + timestampMillis);

            String msgContent = sb.toString();//【抖音】验证码427826，用于绑定手机，5分钟内有效。验证码提供给他人可能导致账号被盗，请勿泄露，谨防被骗。

            String substring = msgContent.substring(msgContent.indexOf("码")+1, msgContent.indexOf('，'));
            et_code.setText(substring);
//            Toast.makeText(context, "接收到 短信验证码:"+substring, Toast.LENGTH_SHORT).show();
//        abortBroadcast();
        }

    }
}

